<?php

App::uses("CrawlUtility", "Utility");
App::uses("Charset", "Lib");
App::uses('RequestFacade', 'Network');

class TaobaoPromotionsController extends TaobaoAppController {

    public $name = 'TaobaoPromotions';


    /* 折扣 */

    public function admin_get() {
        $page = intval($this->request->query['page']) ? intval($this->request->query['page']) : 1;
        $pagesize = 20;

        do {
            $items = $this->Taobaoke->find('all', array(
                        'conditions' => array('published' => 1, 'deleted' => 0),
                        'limit' => $pagesize,
                        'fields' => array('num_iid'),
                        'page' => $page,
                        'order' => 'volume desc'
                    ));
            foreach ($items as $item) {
                $num_iid = $item['Taobaoke']['num_iid'];

                // 删除旧的后，再考虑其他，防止优惠信息过期，对用户造成不好影响
                $delete_flag = $this->TaobaoPromotion->deleteAll(array('num_iid' => $num_iid), true, true);
                $re = $this->admin_getpromotion($num_iid);
                if ($re) {
                    echo 'Get ' . $num_iid . " success.\r\n";
                } else {
                    echo 'Get ' . $num_iid . " false.\r\n";
                }
                sleep(1);
            }
            echo "get page $page \r\n";
            $page++;
        } while (count($items) == $pagesize);

        $this->__message(__('over'), '#', 999999);
    }

    public function admin_saecron_get(){
    	$page = intval($this->request->query['page']) ? intval($this->request->query['page']) : 1;
        $pagesize = 10;
		$items = $this->Taobaoke->find('all', array(
                    'conditions' => array('published' => 1, 'deleted' => 0),
                    'limit' => $pagesize,
                    'fields' => array('num_iid'),
                    'page' => $page,
                    'order' => 'volume desc'
        ));
        foreach ($items as $item) {
            $num_iid = $item['Taobaoke']['num_iid'];
            // 删除旧的后，再考虑其他，防止优惠信息过期，对用户造成不好影响
            $delete_flag = $this->TaobaoPromotion->deleteAll(array('num_iid' => $num_iid), true, true);
            $re = $this->admin_getpromotion($num_iid);
            if ($re) {
                echo 'Get ' . $num_iid . " success.\r\n";
            } else {
                echo 'Get ' . $num_iid . " false.\r\n";
            }
        }
        echo "get page $page \r\n";
    	if (count($items) == $pagesize && empty($_GET['skip_next'])){
			$this->TaskQueue->add('/admin/taobao/taobao_promotions/saecron_get?page='.($page+1));
        }
        exit;
    }
    /**
     * 获取商品的优惠信息。淘宝和天猫的处理方法不一样
     * @param $num__iid  商品编号 for test,12224681317, 5210490640,,,
     */
    public function admin_getpromotion($num_iid) {
    	App::uses('Charset', 'Lib');
    	$itemurl = 'http://detail.tmall.com/item.htm?id='.$num_iid;
    	//$itemurl = 'http://item.taobao.com/item.htm?id='.$num_iid;
    	$request = array(
    			'header' => array(
    					'Referer' => $loginurl,
    					'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2',
    			),
    	);
    	$isTmall = $isTaobao = false;
    	//打开登录页，初始化种入一些cookie。
    	$response = RequestFacade::get($itemurl, array(), $request);
    	$content = $response->body();
    	if(preg_match('/"initApi"\s*:\s*"(.+?)",/is',$content,$matches)){ // 天猫
    		$isTmall = true;
    		$url = $matches[1];
    		$request['header']['Referer'] = 'http://detail.tmall.com/item.htm?id='.$num_iid;
    	}
    	elseif(preg_match('/"apiPromoData":\s*"(.+?)",/is',$content,$matches)){
    		$isTaobao = true;
    		$url = $matches[1];
    		$request['header']['Referer'] = 'http://item.taobao.com/item.htm?id='.$num_iid;
    	}
//     	echo $url;
//     	exit;
    	$response = RequestFacade::get($url, array(), $request);
    	$content = trim($response->body());
    	$content = Charset::gbk_utf8($content);
    	
    	$taobaokeinfo = $this->Taobaoke->find('first', array('conditions' => array('num_iid' => $num_iid),));
    	
    	$sr_price = $taobaokeinfo['Taobaoke']['price'];
    	
    	$this->TaobaoPromotion->create();
    	
    	if($isTmall){    		
    		$promot = jsonToArray($content);
    		$priceInfo = $promot['defaultModel']['itemPriceResultDO']['priceInfo'];
    		$priceInfo = current($priceInfo); //['def']['promPrice']
    		$priceInfo = $priceInfo['promPrice'];
    		$promotion_info = array();
    		$promotion_info['name'] = $priceInfo['promText'];
    		$promotion_info['promType'] = $priceInfo['type'];
    		$promotion_info['promName'] = $priceInfo['promText'];
    		$promotion_info['promPrice'] = $priceInfo['price'];    		
    		$promotion_info['num_iid'] = $num_iid;
    		if(empty($promotion_info['promPrice'])){
    			return false;
    		}
    		$promotion_info['discountValue'] = round($promotion_info['promPrice'] * 10 / $sr_price, 2);
    		$this->TaobaoPromotion->save($promotion_info);
    	}
    	elseif($isTaobao){
    		$content = trim(str_replace('TB.PromoData =','',$content));
    		$promot = jsonToArray($content);
    		$priceInfo = $promot['def'][0];
    		
    		$promotion_info = array();
    		// promList
    		$promotion_info['name'] = $priceInfo['type'];
    		$promotion_info['promType'] = $priceInfo['type'];
    		$promotion_info['promName'] = $priceInfo['type'];
    		$promotion_info['promPrice'] = $priceInfo['price'];    		
    		$promotion_info['num_iid'] = $num_iid;
    		if(empty($promotion_info['promPrice'])){
    			return false;
    		}
    		$promotion_info['discountValue'] = round($promotion_info['promPrice'] * 10 / $sr_price, 2);
    		$this->TaobaoPromotion->save($promotion_info);
    	}
    	print_r($promotion_info);
//     	print_r(json_decode($content,true));
    	return true;
    	
    	//
    	/**
    	 * "initApi" : "http://mdskip.taobao.com/core/initItemDetail.htm?deliveryOption=0&ump=true&trialErrNum=0&isSpu=false&isIFC=false&sellerUserTag4=137573205379&notAllowOriginPrice=false&sellerUserTag2=18020051827294220&sellerUserTag3=562949987008640&isForbidBuyItem=false&isAreaSell=false&isWrtTag=false&tmallBuySupport=true&isMeizTry=false&itemTags=1346,1478,2049,2882,3974,4166,6146,7810,7938,8002,8258,8578&sellerUserTag=307827232&household=false&tgTag=false&itemId=12700800691&isUseInventoryCenter=true&itemWeight=0&isSecKill=false&isApparel=true&service3C=false&cartEnable=true",
    	 */
    	//http://mdskip.taobao.com/core/initItemDetail.htm?deliveryOption=0&ump=true&trialErrNum=0&isSpu=false&isIFC=false&sellerUserTag4=137573205379&notAllowOriginPrice=false&sellerUserTag2=18020051827294220&sellerUserTag3=562949987008640&isForbidBuyItem=false&isAreaSell=false&isWrtTag=false&tmallBuySupport=true&isMeizTry=false&itemTags=1346,1478,2049,2882,3974,4166,6146,7810,7938,8002,8258,8578&sellerUserTag=307827232&household=false&tgTag=false&itemId=12700800691&isUseInventoryCenter=true&itemWeight=0&isSecKill=false&isApparel=true&service3C=false&cartEnable=true&callback=jsonp1352303832688_0&ip=&campaignId=&key=&abt=&cat_id=&q=&ref=
    	/**
    	 *       "apiPromoData": "http://ajax.tbcdn.cn/json/promotionListn.htm?rcid=16&sts=307851776,1756404009370910788,144115188109443200,70373039178755&chnl=pc&price=5300&itemId=12556990495&sellerId=637529642&shopId=",
    	 */
    	//http://ajax.tbcdn.cn/json/promotionListn.htm?rcid=16&sts=307851776,1756404009370910788,144115188109443200,70373039178755&chnl=pc&price=5300&itemId=12556990495&sellerId=637529642&shopId=&cna=mrjTCEB%2BlE0CAXt6hajbwpjn&ref=http%3A%2F%2Fs.click.taobao.com%2Ft_js%3Ftu%3Dhttp%253A%252F%252Fs.click.taobao.com%252Ft%253Fe%253DzGU34CA7K%25252BPkqB07S4%25252FK0CITy7klxn%25252F7bvn0ay1FUepDkEIY%25252F2HPjF7k%25252B%25252Bx0HmMS%25252Bow0TZdk8q4RgoXMxDnoAu0LMDuRmjl1uYwA0WhbrE%25252B7qi8CUaHhaPZh32AUypfDYowpptBHIWrh6VYEcSbkWRJUThKu4Oh512ZLeH0dJS%25252FpGfgZ7DRBlogbJy%25252B7%25252FP8r%2526spm%253D2014.12336677.1.0%2526ref%253Dhttp%25253A%25252F%25252Flocalhost%25252FSaeProj%25252Fideacms%25252F3%25252Fmanage%25252Fadmin%25252Ftaobao%25252Ftaobaokes%25252Fproducts%25252F16.html%2526et%253DjFBB3CgMLZLLng%25253D%25253D&buyerId=192339084&nick=ideamuster&tg=1048576&tg2=4415226388488&tg3=72057594037927936&tg4=13581167626289152
        $promotion_url = "http://marketing.taobao.com/home/promotion/item_promotion_list.do?itemId=" . $num_iid;
        $promote = CrawlUtility::getRomoteUrlContent($promotion_url);
        preg_match("/{.+}/s", $promote->body, $matches);

        $jsoncode = $matches[0];
        if (empty($jsoncode)){
        	return $this->admin_getPromotionByPreg($num_iid);
        }
        $jsoncode = Charset::gbk_utf8($jsoncode);
        $promData = jsonToArray($jsoncode);
        //print_r($promData);
        if ($promData['isSuccess'] == 'T' && !empty($promData['promList'])) {
            $priceInfo = $promData['promList'][0];
            $policyList = $priceInfo['policyList'][0];
            if (empty($policyList)) {
            	return $this->admin_getPromotionByPreg($num_iid);
            }
            $this->TaobaoPromotion->create();
            $promotion_info = array();
            // promList
            $promotion_info['name'] = $priceInfo['iconTitle'];
            $promotion_info['promId'] = $priceInfo['promId'];
            $promotion_info['promType'] = $priceInfo['promType'];
            $promotion_info['promName'] = $priceInfo['promName'];
            $promotion_info['showPrice'] = $priceInfo['showPrice'];
            $promotion_info['showPoint'] = $priceInfo['showPoint'];
            $promotion_info['showIcon'] = $priceInfo['showIcon'];
            // policyList
            $promotion_info['policyId'] = $policyList['policyId'];
            $promotion_info['groupName'] = $policyList['groupName'];
            $promotion_info['iconFile'] = $policyList['iconFile'];
            $promotion_info['discountValue'] = $policyList['discountValue'];
            if ($policyList['discountType'] == 1) {
                // 若为直接降价，则转换成折扣的形式
                $policyList['discountType'] = 2;
                $promotion_info['discountValue'] = round($policyList['promPrice'] * 10 / ($promotion_info['discountValue'] + $policyList['promPrice']), 2);
            }
            $promotion_info['discountType'] = $policyList['discountType'];
            $promotion_info['promPrice'] = $policyList['promPrice'];
            $promotion_info['num_iid'] = $num_iid;
            $this->TaobaoPromotion->save($promotion_info);
            return true;
        }
        else{
        	return $this->admin_getPromotionByPreg($num_iid);
        }
        return false;
    }
    
    public function  admin_getPromotionByPreg($num_iid){
    	//http://marketing.taobao.com/home/promotion/item_promotion_list.do?itemId=12678875747
    	//http://detail.tmall.com/item.htm?id=12678875747
//    	$num_iid = 12678875747;
    	$this->autoRender =false;
    	$promotion_url = "http://detail.tmall.com/item.htm?id=" . $num_iid;
    	$promote = CrawlUtility::getRomoteUrlContent($promotion_url);        
        $promote = Charset::gbk_utf8($promote->body);
        /*
         * 
         * <ul id="Ul_promo" class="tb-clearfix">\s<li><span id="J_ImgLimitProm" class="tb-icon tb-limit-prom" title="限时促销"></span><strong class="tb-price" id="J_SpanLimitProm">129.00</strong>元</li>
                            <li>(剩 <em id="J_EmLimitPromCountdown">-</em> 结束)</li>\s</ul>
         */       
        preg_match('/<ul id="Ul_promo" class="tb-clearfix">\s+<li><span id="J_ImgLimitProm" class="tb-icon tb-limit-prom" title="(.+?)"><\/span><strong class="tb-price" id="J_SpanLimitProm">(.+?)<\/strong>.+?<\/li>\s+<li>.+?<\/li>\s+?<\/ul>/is', $promote, $matches);
        
        if(!empty($matches[1])){
	        $this->TaobaoPromotion->create();	        
	        $item = $this->Taobaoke->find('first', array(
	                    'conditions' => array('published' => 1, 'deleted' => 0,'num_iid' => $num_iid),
	                    'fields' => array('price','id','num_iid'),
	        ));	        
	        $promotion_info = array();
	        // promList
	        $promotion_info['name'] = $matches[1];
	        $promotion_info['promType'] = 1;
	        $promotion_info['promName'] = $matches[1];
	        $promotion_info['groupName'] = $matches[1];
	        
	        $promotion_info['discountType'] = 2;
	        $promotion_info['promPrice'] = $matches[2];
	        if($item['Taobaoke']['price']){
	        	$promotion_info['discountValue'] = round($promotion_info['promPrice'] * 10 / ($item['Taobaoke']['price']), 2);
	        }	        
	        $promotion_info['num_iid'] = $num_iid;
	        //print_r($promotion_info);
	        $this->TaobaoPromotion->save($promotion_info);  
	        return true;
        }
        else{
        	return false;
        }
    }

}

?>